package com.lenovo.leos.filebrowser.ui;//xieqm 110308

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.text.InputFilter;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.operation.FileDelete;
import com.lenovo.leos.filebrowser.engine.operation.FileOp;
import com.lenovo.leos.filebrowser.engine.operation.FileRename;
import com.lenovo.leos.filebrowser.engine.operation.FileShare;
import com.lenovo.leos.filebrowser.engine.util.FileClipBoard;
import com.lenovo.leos.filebrowser.engine.util.FileHandler;
import com.lenovo.leos.filebrowser.engine.util.FileHandler.MsgHandleFunc;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.filebrowser.netdisk.ErrorMessageDialog;
import com.lenovo.leos.filebrowser.netdisk.NetDiskConstant;
import com.lenovo.leos.filebrowser.netdisk.NetDiskManager;
import com.lenovo.leos.filebrowser.netdisk.NetDiskOpResult;
import com.lenovo.leos.filebrowser.netdisk.NetFile;
import com.lenovo.leos.filebrowser.netdisk.ProgressMessageDialog;

public class FileSearcher extends BaseActivity implements
		OnTitleIconClickListener, FileFilter, OnItemClickListener/*
																 * implements
																 * TextWatcher
																 */{
	private static final String TAG = "FileSearcherActivity";

	private File refreshFile = null; // add 2011-01-10 by xie
	private static final String ZIP_MIMETYPE = "compressor/zip";// add xieqm
																// 110112

	private enum DISPLAYMODE {
		ABSOLUTE, RELATIVE
	};

	public final static int _LIST = 10;
	public final static int _SELECT = 11;

	protected final int SUB_ACTIVITY_REQUEST_CODE = 1337;
	// private final String localroot = Constant.localroot;
	private final String sdroot = Constant.sdroot;
	// private final String uroot = Constant.uroot;
	private final String ZIPENDSTRING = ".zip";
	// private enum LOCATION{LOCAL,SDCARD,UDISK};
	// private LOCATION location = LOCATION.LOCAL;
	public static boolean isUDiskMnt = false;

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;

	/** Contains directories and files together */
	private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
	/** Dir separate for sorting */
	List<IconifiedText> mListDir = new ArrayList<IconifiedText>();
	/** Files separate for sorting */
	List<IconifiedText> mListFile = new ArrayList<IconifiedText>();
	/** SysDir separate for sorting */
	List<IconifiedText> mListSys = new ArrayList<IconifiedText>();

	private File currentDirectory = new File(sdroot);

	// a list contains all selected file objects;
	public static ArrayList<File> MarkedFile = new ArrayList<File>();
	// flag to identify cut or copy operation.
	// The activities of operation menu item(paste) are depends on cut_copy
	public static boolean cut_copy = false;

	public enum OPTYPE {
		CUT, COPY
	};

	public static OPTYPE opType;
	// the state of the progress in.
	public static int State;

	// define menu options ID

	private static final int DEL_ID = Menu.FIRST;
	private static final int CUT_ID = Menu.FIRST + 1;
	private static final int COPY_ID = Menu.FIRST + 2;
	private static final int COMPRESS_ID = Menu.FIRST + 3;

	private static final int RENAME_ID = Menu.FIRST + 4;
	private static final int DECOMPRESS_ID = Menu.FIRST + 5;
	private static final int ATTRIDIS_ID = Menu.FIRST + 6;
	private static final int SEND_ID = Menu.FIRST + 7;
	private static final int PRE_UPLOAD = Menu.FIRST + 8;

	FileSearchAdapter itemList;
	// add by PH 091011
	private static MimeTypes mMimeTypes = null;
	// end PH 091011
	// add by PH 091012
	public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
	// end PH 091012
	// add by PH 091013
	public static int officeFlag;
	String mInitDefaultPath;
	// end PH 091013
	boolean openfile = false;

	private static boolean nothing = false;
	// add by PH 091024
	private static final int FILE_NAME_NUM_MAX = 85;
	private static final int OFFICE_FILE_NAME_NUM_MAX = 81;

	boolean mToCloseSend = false;
	private boolean mRegisterReceiver = false;
	File searchFile;
	boolean search = false;
	boolean searchDecom = false;
	String searchpath;
	String searchpathnofile;
	// private boolean mChecked = false;
	InputMethodManager inputMethodManager;
	private boolean sdRemoved = false;
	// int length;
	// private ContentResolver mResolver = null;
	private File[] mFilesOnCurDir;
	private ProgressDialog mProgressDialog;
	private MyAttributeThread mAttributeThread = null;
	MyBrowserToHandler myBrowserToHandler = null;
	private static final int BROWSETO_RESULT_MSG = 40000;
	private static final int ATTRIBUTE_RESULT_MSG = 50000;
	boolean browsetoThreadFlag = false;
	boolean SdcardUnmounted = false;
	boolean mBrowseToThreadStop = false;
	private int subDirNum = 0;
	private int fileNum = 0;
	private long fileSize = 0;
	String arrfilename;
	String arrsubdir;
	String arrfilenum;
	String arrtotalfileSize;
	String arrmodifyDate;
	// View mtextEntryView;
	TextView mSubFile;
	TextView mTotalSize;
	TextView mSubDir;
	ListView mlvContent;

	// add by xieqm 110225
	private static final boolean TAG_FLAG = true;
	public final static int RESULT_LIST = 12;
	private static String projectState;
	private static FileSearcher instance = new FileSearcher();
	private static final int SEARCH_RESULT_MSG = 1000;
	private static final int SEARCH_RESULT_TOOMACH_MSG = 2000;
	private static final int SEARCH_RESULT_MAX_NUM = 10000;
	private MySearchThread mSearchThread = null;
	String searchStr;
	String path;
	boolean mFirstinit = true;
	ProgressDialog progressDialog = null;
	boolean flag;
	TextView tView;
	private String mUpload;
	private String[] uploadFile;
	private boolean[] uploadFileTypes;

	private static final int MSG_LOGIN_OK = 100000;
	private static final int MSG_LOGIN_FAILED = 100001;

	NetDiskManager mndManager = null;
	LoginHandler mHandler = new LoginHandler(Looper.myLooper());

	long mlCurOp = -1;

	ArrayList<File> fileArray = null;

	public static FileSearcher getInstance() {
		return instance;
	}

	private class LoginHandler extends Handler {
		public LoginHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "==> handleMessage");

			if (msg.what == MSG_LOGIN_OK) {
				ProgressMessageDialog.cancelDialog();
				Intent intent = new Intent();
				String mUpload = DirDefines.UPLOAD;
				mUpload = DirDefines.UPLOAD;
				intent.putExtra("mUpload", mUpload);
				intent.putExtra("uploadFile", uploadFile);
				intent.putExtra("projectState", projectState);
				intent.putExtra("uploadFileTypes", uploadFileTypes);
				if (TAG_FLAG) {
					Log.d(TAG, "the uploadFile[0] is ================ "
							+ uploadFile[0]);
					Log.d(TAG, "the uploadFileTypes[0] is ================ "
							+ uploadFileTypes[0]);
				}
				intent.setClass(
						FileSearcher.this,
						com.lenovo.leos.filebrowser.netdisk.LenovoInterfaceActivity.class);
				startActivity(intent);
				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				finish();
			} else if (msg.what == MSG_LOGIN_FAILED) {
				ProgressMessageDialog.cancelDialog();
				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				Toast.makeText(FileSearcher.this, "login net disk failed",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private class LoginThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public LoginThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mStop = true;
		}

		public void onLoginOk() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_OK, 0, 0, null);
			mHandler.sendMessage(msg);
		}

		public void onLoginFailed() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_FAILED, 0, 0, null);
			mHandler.sendMessage(msg);
		}
	}

	private class MyBrowserToHandler extends Handler {
		public MyBrowserToHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == BROWSETO_RESULT_MSG) {

				browsetoThreadFlag = false;
			} else if (msg.what == ATTRIBUTE_RESULT_MSG) {
				arrtotalfileSize = transferSize(fileSize);
				mSubFile.setText(getResources().getString(R.string.filenum)
						+ fileNum);
				mTotalSize.setText(getResources().getString(R.string.totalsize)
						+ arrtotalfileSize);
				mSubDir.setText(getResources().getString(R.string.subdir)
						+ subDirNum);
			} else if (msg.what == SEARCH_RESULT_MSG) {
				Log.d(TAG, "SEARCH_RESULT_MSG===itemList----------------------"
						+ itemList);
				Log.i(TAG, "the size of fileArray is " + fileArray.size());
				sortedFileList(fileArray);
				Log.i(TAG, "the size of directoryEntries is "
						+ directoryEntries.size());
				itemList.setListItems(directoryEntries);
				mlvContent.setAdapter(itemList);// setListAdapter(itemList);
				if (fileArray == null || fileArray.size() == 0) {
					tView.setVisibility(View.VISIBLE);
					tView.setText(R.string.find_nothing);
				} else {
					tView.setVisibility(View.GONE);
				}
			} else if (msg.what == SEARCH_RESULT_TOOMACH_MSG) {
				mSearchThread.toStop();
				mlvContent.setAdapter(itemList);// setListAdapter(itemList);
				tView.setVisibility(View.GONE);
				Toast.makeText(FileSearcher.this,
						R.string.search_result_toomach, 2).show();
			}
		}

	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		projectState = getIntent().getStringExtra("projectState");
		if (TAG_FLAG) {
			Log.d(TAG, "state=======================" + projectState);
		}

		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilter.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilter.addDataScheme("file");
		registerReceiver(SdCardIntentReceiver, commandFilter);
		mRegisterReceiver = true;
		path = getIntent().getExtras().getString("path");
		searchStr = getIntent().getExtras().getString("searchStr");
		Log.d(TAG, "path=======================" + path);
		Log.d(TAG, "searchStr=======================" + searchStr);
		MarkedFile.clear();

		fileArray = new ArrayList<File>();

		initMimeTypes();
		initState();
		if (icicle == null) {
			if (mFirstinit) {
				runSerch();
			}
		} else {
			fileArray = (ArrayList<File>) icicle.getSerializable("result");
			flag = icicle.getBoolean("flag");
			runSerch();
		}
		registerForContextMenu(mlvContent);
	}

	private void initState() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%initState");
		// set the layout for List state
		setContentView(R.layout.filesearchlist);
		setTitle(R.string.search_result);
		this.customTitleIcon(0, 0, 0, this);
		tView = (TextView) findViewById(R.id.empty);
		if (TAG_FLAG) {
			for (int i = 0; i < directoryEntries.size(); i++) {
				Log.d(TAG,
						"directoryEntries===========" + directoryEntries.get(i));
			}
		}
		itemList = new FileSearchAdapter(this, this.directoryEntries);
		mlvContent = (ListView) findViewById(android.R.id.list);
		myBrowserToHandler = new MyBrowserToHandler(Looper.myLooper());
		// register a ContextMenu for the current listview
		mlvContent.setOnItemClickListener(this);
		registerForContextMenu(mlvContent);
	}

	// end

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "*************onDestroy***************");
		if (mRegisterReceiver) {
			unregisterReceiver(SdCardIntentReceiver);
			// Log.i(TAG, "*********OnDestroy unregisterReceiver *********");
		}
		if (browsetoThreadFlag) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
		}
		if (mAttributeThread != null)
			mAttributeThread = null;

		if (null != mndManager) {
			mndManager.unbindOpService();
			mndManager = null;
		}

	}

	public void myFileList(File file) {
		Log.d(TAG, "==> myFileList");

		if (file.isHidden()) {
			return;
		}

		if (fileArray.size() > SEARCH_RESULT_MAX_NUM) {
			mSearchThread.onSearchResultToomach();
			return;
		}

		if (file.isDirectory()) {
			File[] files = file.listFiles(this);
			if (files == null) {
				return;
			}
			for (int i = 0; i < files.length; i++) {
				if (mSearchThread.mStop)
					break;
				if (files[i].isHidden()) {
					continue;
				}

				Log.d(TAG, "the file is " + files[i].getAbsolutePath());
				boolean bContained = files[i].getName().toLowerCase()
						.contains(searchStr.toLowerCase());
				Log.d(TAG, "is is what we want or not : " + bContained);
				if (files[i].isDirectory()) {
					if (bContained) {
						if (fileArray.size() > SEARCH_RESULT_MAX_NUM) {
							mSearchThread.onSearchResultToomach();
							return;
						}

						fileArray.add(files[i]);
					}
					myFileList(files[i]);
				} else {
					if (fileArray.size() > SEARCH_RESULT_MAX_NUM) {
						mSearchThread.onSearchResultToomach();
						return;
					}

					fileArray.add(files[i]);
				}
			}
		} else {
			boolean bContained = file.getName().toLowerCase()
					.contains(searchStr.toLowerCase());
			if (bContained) {
				if (fileArray.size() > SEARCH_RESULT_MAX_NUM) {
					mSearchThread.onSearchResultToomach();
					return;
				}

				fileArray.add(file);
			}
		}
	}

	private class MySearchThread extends Thread {
		private Context mContext;
		boolean mStop = false;
		boolean mResume = true;
		protected PowerManager.WakeLock mWakeLock;

		public MySearchThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mResume = true;
			mStop = true;
		}

		private void onSearchResult() {
			Message msg = myBrowserToHandler.obtainMessage(SEARCH_RESULT_MSG,
					0, 0, null);
			myBrowserToHandler.sendMessage(msg);
		}

		private void onSearchResultToomach() {
			Message msg = myBrowserToHandler.obtainMessage(
					SEARCH_RESULT_TOOMACH_MSG, 0, 0, null);
			myBrowserToHandler.sendMessage(msg);
		}

		private void getFiles(File file, String s) {
			Log.d(TAG, "-----------------getFiles()------------------");
			myFileList(file);
		}

	}

	private void runSerch() {
		mFirstinit = false;
		progressDialog = new ProgressDialog(FileSearcher.this);
		progressDialog.setTitle(R.string.menu_search);
		progressDialog.setMessage(getString(R.string.isSearching));
		progressDialog.setButton(getString(R.string.cancle),
				new ProgressDialog.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int which) {
						if (mSearchThread != null)
							mSearchThread.toStop();
						FileSearcher.this.finish();
					}
				});
		progressDialog.show();
		mSearchThread = new MySearchThread(this) {
			public void run() {
				mWakeLock.acquire();
				if (!flag && !mStop) {
					Log.d(TAG, "-----------------runSerch()------------------"
							+ searchStr);
					mSearchThread.getFiles(new File(path), searchStr);
					if (!mStop)
						mSearchThread.onSearchResult();
				}
				if (!flag) {
					progressDialog.dismiss();
					progressDialog = null;
				}
				mWakeLock.release();
			}
		};
		mSearchThread.start();
	}

	private class MyBrowseToThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public MyBrowseToThread(Context context) {
			// mStop = false;
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			// mResume = true;
			mStop = true;
		}

		private void onBrowseToResult() {
			Message msg = myBrowserToHandler.obtainMessage(BROWSETO_RESULT_MSG,
					0, 0, null);
			myBrowserToHandler.sendMessage(msg);
		}
	}

	private class MyAttributeThread extends Thread {
		Context mContext;
		boolean mStop = false;

		public MyAttributeThread(Context context) {
			mContext = context;
		}

		public void toStop() {
			mStop = true;
		}

		public void onAttributeResult() {
			Message msg = myBrowserToHandler.obtainMessage(
					ATTRIBUTE_RESULT_MSG, 0, 0, null);
			myBrowserToHandler.sendMessage(msg);
		}

	}

	// add by PH 091011
	private void initMimeTypes() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%initMimeTypes");
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in = getResources().getXml(
			// com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = getResources().getXml(R.xml.mimetypes);
			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				Log.e(TAG, "************************** XmlPullParserException",
						e);
				throw new RuntimeException(
						"*************************** XmlPullParserException");
			} catch (IOException e) {
				Log.e(TAG, "************************** IOException", e);
				throw new RuntimeException(
						"************************** IOException", e);
			}
		}
	}

	// add by PH 091016
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (icon == null) {
			PackageManager pm = getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setType(mimetype);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else if (mimetype.equals(ZIP_MIMETYPE)) { // add 2010-12-13 by xqm
				icon = getResources().getDrawable(R.drawable.zip);
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = getResources().getDrawable(R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	private void addAllElements(List<IconifiedText> addTo,
			List<IconifiedText> addFrom) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%addAllElements");
		for (int i = 0; i < addFrom.size(); i++) {
			addTo.add(addFrom.get(i));
		}
	}

	private void addIconifiedTextToList(IconifiedText item,
			List<IconifiedText> list) {
		list.add(item);
		return;
	}

	private void sortedFileList(List<File> files) {
		Log.i(TAG, "==> sortedFileList");

		if (files == null) {
			return;
		}

		Drawable currentSysIcon = getResources().getDrawable(
				R.drawable.icon_folder_sys);
		Drawable currentUsrIcon = getResources().getDrawable(
				R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		this.mListDir.clear();
		this.mListFile.clear();
		this.mListSys.clear();
		this.directoryEntries.clear();

		Log.i(TAG, "the size of files is " + files.size());

		for (File currentFile : files) {
			Log.i(TAG, "the current file is " + currentFile.getAbsolutePath());
			/*
			 * add 2010-11-4 xie
			 */
			if (currentFile.isDirectory()) {
				if (!Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					// if (currentIcon == null)
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						addIconifiedTextToList(new IconifiedText(
								currentUsrIcon, currentFile, false), mListDir);
						break;
					}
				} else if (Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						addIconifiedTextToList(new IconifiedText(
								currentSysIcon, currentFile, true), mListSys);
						break;
					}
				}
			} else {
				String fileName = currentFile.getName();
				// add by PH 091016
				String mimetype = mMimeTypes
						.getMimeType(fileName.toLowerCase());
				if (mimetype == null) {
					if (FileUtil.getExtension(fileName).equals(".p12")) {
						fileIcon = getResources().getDrawable(
								R.drawable.ic_menu_login);
					} else {
						fileIcon = getResources().getDrawable(
								R.drawable.icon_unknown_file);
					}
				} else {
					fileIcon = getDrawableForMimetype(mimetype);
				}
				// end PH 091016

				switch (this.displayMode) {
				case ABSOLUTE:
				case RELATIVE:
					Log.i(TAG,
							"the current file = "
									+ currentFile.getAbsolutePath());
					addIconifiedTextToList(new IconifiedText(fileIcon,
							currentFile, false), mListFile);
					Log.i(TAG, "the new size is " + mListFile.size());
					break;
				}
			}
		}

		// Log.d(TAG,
		// "###################### directoryEntries = "+directoryEntries);
		addAllElements(directoryEntries, mListSys);
		addAllElements(directoryEntries, mListDir);
		addAllElements(directoryEntries, mListFile);
		Log.i(TAG, "the size of mListFile is " + mListFile.size());
	}

	/**
	 * Checks whether checkItsEnd ends with one of the Strings from fileEndings
	 */
	private static boolean checkEndsWithInStringArray(String checkItsEnd,
			String[] fileEndings) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%checkEndsWithInStringArray");
		for (String aEnd : fileEndings) {
			if (checkItsEnd.toLowerCase().endsWith(aEnd))
				return true;
		}
		return false;
	}

	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onCreateContextMenu");
		super.onCreateContextMenu(menu, view, menuInfo);
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		} catch (ClassCastException e) {
			Log.e(TAG, "***********bad menuInfo************", e);
			return;
		}
		IconifiedText ob = (IconifiedText) mlvContent.getAdapter().getItem(
				info.position);
		if (ob == null || ob.getFile() == null)
			return;
		if (ob.getFile().isFile()) {
			menu.add(0, DEL_ID, 0, R.string.menu_delete);
			menu.add(0, CUT_ID, 0, R.string.menu_cut);
			menu.add(0, COPY_ID, 0, R.string.menu_copy);
			menu.add(0, PRE_UPLOAD, 0, R.string.upload);
			menu.add(0, SEND_ID, 0, R.string.menu_send);

			if (FileUtil.getExtension(ob.getText()).equals(".zip")) {
				menu.add(0, DECOMPRESS_ID, 0, R.string.menu_decompress);
				menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
			} else {
				menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
			}

			menu.add(0, RENAME_ID, 0, R.string.menu_rename);
			menu.add(0, ATTRIDIS_ID, 0, R.string.menu_disattri);
		}
		/*
		 * add 2010-11-4 xie
		 */
		if (ob.getFile().isDirectory()) {
			// Log.d(TAG, "*************isDirectory ********* ");
			if (Constant.isSysOrReservedDir(this, ob.getFile()) == false) {
				menu.add(0, DEL_ID, 0, R.string.menu_delete);
				menu.add(0, CUT_ID, 0, R.string.menu_cut);
			}
			menu.add(0, COPY_ID, 0, R.string.menu_copy);
			menu.add(0, PRE_UPLOAD, 0, R.string.upload);
			menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
			if (Constant.isSysOrReservedDir(this, ob.getFile()) == false) {
				menu.add(0, RENAME_ID, 0, R.string.menu_rename);
			}
			menu.add(0, ATTRIDIS_ID, 0, R.string.menu_disattri);
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onContextItemSelected");
		cut_copy = false;
		this.itemList.notifyDataSetChanged();
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
		}
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final IconifiedText ob = (IconifiedText) mlvContent.getAdapter()
				.getItem(info.position);
		if (ob == null || ob.getFile() == null)
			return false;
		MarkedFile.add(ob.getFile());
		switch (item.getItemId()) {
		case DEL_ID:
			delFile();
			break;
		case COPY_ID:
			opType = OPTYPE.COPY;
			cut_copy = true;
			FileClipBoard fcbMarked = FileClipBoard.getInstance();
			fcbMarked.clear();
			fcbMarked.setOperation(FileClipBoard.OP_COPY);
			for (int i = 0; i < MarkedFile.size(); i++) {
				File file = MarkedFile.get(i);
				if (!fcbMarked.hasIt(file)) {
					fcbMarked.addFile(file);
				}
			}
			break;
		case PRE_UPLOAD:
			if (TAG_FLAG)
				Log.d(TAG, "=================PRE_UPLOAD==========");
			uploadFile = new String[1];
			uploadFileTypes = new boolean[1];
			uploadFile[0] = ob.getFile().getAbsolutePath();
			uploadFileTypes[0] = ob.getFile().isDirectory();
			preUpload();
			break;
		case CUT_ID:
			// set the both cut-or-copy flags
			opType = OPTYPE.CUT;
			cut_copy = true;
			// darken the selected items
			darkSelectedItem();
			CutAndCopyVo.getInstance().setSearchPaste(true);
			CutAndCopyVo.getInstance().setCut_copy(cut_copy);
			CutAndCopyVo.getInstance().setCutFile(MarkedFile);
			// refreshScr();
			break;
		case COMPRESS_ID:
			onCompress();
			break;
		case DECOMPRESS_ID:
			onDecompress(ob.getFile());
			break;
		case RENAME_ID:
			if (false) {// NetDiskManager.isDownLoadWork(ob.getFile().getAbsolutePath())
				Log.d(TAG, "==> isDownLoadWork");
				ErrorMessageDialog.showMessageDialog(FileSearcher.this,
						getString(R.string.download_no_finish));
			} else if (false) {// NetDiskManager.isUpLoadWork(ob.getFile().getAbsolutePath())
				Log.d(TAG, "==> isUpLoadWork");
				ErrorMessageDialog.showMessageDialog(FileSearcher.this,
						getString(R.string.upload_no_finish));
			} else {
				onRename(ob.getFile());
			}
			break;
		case ATTRIDIS_ID:
			disAttri();
			break;
		case SEND_ID:
			sendFile(ob.getFile());
			break;
		default:
			return super.onContextItemSelected(item);
		}
		return true;

	}

	private void preUpload() {
		new AlertDialog.Builder(FileSearcher.this)
				.setTitle(R.string.upload)
				.setMessage(R.string.upload_detail)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								loginLenovo();
							}
						})
				.setNeutralButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	private void loginLenovo() {
		mndManager = NetDiskManager.getInstance(this);
		if (null == NetDiskConstant.NET_DISK_ROOT) {
			Log.d(TAG, "net disk is null");

			ProgressMessageDialog.showMessageDialog(this,
					getString(R.string.login), getString(R.string.loading));

			mndManager.bindOpService();

			LoginThread mThread = new LoginThread(this) {
				public void run() {

					long id = -1;
					while (true) {
						if (mndManager.isConnected()) {
							id = mndManager.login("xiexie_0101@163.com",
									"123456");
							break;
						} else {
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}

					NetDiskOpResult result = null;

					do {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

						result = mndManager.getResult(id);

						if (null != result)
							break;
					} while (true);

					NetFile nfRoot = null;

					try {
						nfRoot = result.GetRootNetFile();
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (null != nfRoot) {
						NetDiskConstant.NET_DISK_ROOT = nfRoot;
						Log.e(TAG, "the root id is " + nfRoot.getID());
						onLoginOk();
					} else {
						mHandler.post(new Runnable() {

							@Override
							public void run() {
								String errorMsg = NetDiskOpResult
										.strGetErrorMsg();
								if (TAG_FLAG) {
									Log.d(TAG,
											"the errorMsg is ================ "
													+ errorMsg);
									AlertDialog dialog = new AlertDialog.Builder(
											FileSearcher.this)
											.setTitle(
													R.string.switching_directory)
											.setTitle(R.string.remind)
											.setMessage(errorMsg)
											.setPositiveButton(
													R.string.dlg_btn_ok,
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															dialog.cancel();
															ProgressMessageDialog
																	.cancelDialog();
														}
													}).show();
								}
							}
						});
					}

				}
			};

			mThread.start();
		} else {
			if (TAG_FLAG) {
				Log.d(TAG, "net disk is not null");
			}
			Intent intent = new Intent();
			String mUpload = DirDefines.UPLOAD;
			intent.putExtra("projectState", projectState);
			mUpload = DirDefines.UPLOAD;
			intent.putExtra("mUpload", mUpload);
			intent.putExtra("uploadFile", uploadFile);
			intent.putExtra("uploadFileTypes", uploadFileTypes);
			intent.setClass(
					FileSearcher.this,
					com.lenovo.leos.filebrowser.netdisk.LenovoInterfaceActivity.class);
			startActivity(intent);
		}
	}
	private void darkSelectedItem() {
		if (false) {//NetDiskManager.isDownLoadWork(file.getAbsolutePath())
			Log.d(TAG, "==> isDownLoadWork");
			ErrorMessageDialog.showMessageDialog(FileSearcher.this,
					getString(R.string.download_no_finish));
		} else if (false) {//NetDiskManager.isUpLoadWork(file.getAbsolutePath())
			Log.d(TAG, "==> isUpLoadWork");
			ErrorMessageDialog.showMessageDialog(FileSearcher.this,
					getString(R.string.upload_no_finish));
		} else {
			Log.d(TAG, "==> not upload or download");
			curItem();
		}
	}
	
	private void curItem(){
		int i;
		if (MarkedFile.isEmpty()) {
			Toast.makeText(this, R.string.error_file_does_not_exists, 3);
			return;
		}

		FileClipBoard.getInstance().clear();
		FileClipBoard.getInstance().setOperation(FileClipBoard.OP_CUT);
		for (i = 0; i < MarkedFile.size(); i++) {
			FileClipBoard.getInstance().addFile(MarkedFile.get(i));
		}
		for (i = 0; i < directoryEntries.size(); i++) {
			if (MarkedFile.contains(directoryEntries.get(i).getFile())) {
				directoryEntries.get(i).setIsCut(true);
			} else {
				directoryEntries.get(i).setIsCut(false);
			}
		}
	}

	/*
	 * decompress the selected zip file to current directory.
	 */
	private void onDecompress(File file) {
		Log.i(TAG, "%==> decompressFile");

		if (null == file || !file.exists())
			Log.e(TAG, "file is invalid in onDecompress");
		else
			checkThenDecompress(file);
	}

	private void checkThenDecompress(File file) {

		if (FileUtil.isCompressFile(file)) {
			decompressFile(file);
		} else {
			Log.e(TAG,
					"can not decompress this type file in checkThenDecompress");
			Toast.makeText(this, R.string.invalid_compressfile,
					Toast.LENGTH_SHORT).show();
		}
	}

	private void decompressFile(File file) {
		Log.i(TAG,
				"==> decompressFile-------------------"
						+ file.getAbsolutePath());

		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		String fileName = file.getName();
		String zipfile;

		/*
		 * update 2010-11-1 xie
		 */
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, path);

		if (fileName.toLowerCase().endsWith(".zip")) {
			bundle.putBoolean(FileOp.KEY_BOOLEAN_IS_ZIP, true);
			zipfile = path + "/" + fileName;
			bundle.putString(FileOp.KEY_STRING_SRC_FILE_PATH, zipfile);
		} else {
			bundle.putBoolean(FileOp.KEY_BOOLEAN_IS_ZIP, false);
		}
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_DECOMPRESS);
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_DECOMPRESS);
	}

	private void onCompress() {
		FileClipBoard.getInstance().clear();
		Log.i(TAG, "the number in MarkedFile is " + MarkedFile.size());
		for (int i = 0; i < MarkedFile.size(); i++) {
			FileClipBoard.getInstance().addFile(MarkedFile.get(i));
		}

		checkThenCompress();
	}

	private void checkThenCompress() {
		Log.d(TAG, "==> checkThenCompress");

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		if (fcbMarked.isEmpty()) {
			Toast.makeText(this, R.string.compress_alert, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(
				R.layout.compress_dialog_text_entry, null);
		final EditText eText = (EditText) textEntryView
				.findViewById(R.id.filename_edit);

		if (fcbMarked.getFile(0).getName().length() >= 85) {
			eText.setText(Constant.textConvert(this, fcbMarked.getFile(0)
					.getName().substring(0, 81))
					+ Constant.ZIPENDSTRING);
			eText.setSelection(0,
					fcbMarked.getFile(0).getName().substring(0, 81).length());// modefied
																				// by
																				// PH
																				// 091123
		} else {
			eText.setText(Constant.textConvert(this, fcbMarked.getFile(0)
					.getName())
					+ Constant.ZIPENDSTRING);
			eText.setSelection(0, fcbMarked.getFile(0).getName().length());// modefied
																			// by
																			// PH
																			// 091123
		}
		eText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
				Constant.FILE_NAME_NUM_MAX) });

		new AlertDialog.Builder(this)
				.setTitle(R.string.alert_dialog_compress)
				.setView(textEntryView)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// inputMethodManager.hideSoftInputFromWindow(getListView().getWindowToken(),
								// 0);
								String name = eText.getText().toString();
								if (name.length() > 0
										&& name.length() <= Constant.FILE_NAME_NUM_MAX) {
									if (FileUtil.isNameUseable(name, false) == false) {
										Toast.makeText(FileSearcher.this,
												R.string.namebad,
												Toast.LENGTH_SHORT).show();
									} else {
										if (name.endsWith(Constant.ZIPENDSTRING) == false) {
											name += Constant.ZIPENDSTRING;
										}
										compressFile(name);
									}
								} else if (name.length() > Constant.FILE_NAME_NUM_MAX) {
									Log.i(TAG, "$$$$$$$$$$$$$$$name.length()="
											+ name.length());
									Toast.makeText(FileSearcher.this,
											R.string.name_too_long,
											Toast.LENGTH_SHORT).show();// add
																		// by//
																		// PH//
																		// 091024
								} else {
									Toast.makeText(FileSearcher.this,
											R.string.nameempty,
											Toast.LENGTH_SHORT).show();
								}
							}

						})
				.setNegativeButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// User clicked cancel so do some stuff
							}
						}).show();
	}

	/*
	 * compress the selected file or directory in current directory
	 */
	private void compressFile(String rarname) {
		Log.d(TAG, "==> compressFile");

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		fcbMarked.setOperation(FileClipBoard.OP_COMPRESS);

		Log.i(TAG, "the number is " + String.valueOf(fcbMarked.getSize()));

		Bundle bundle = new Bundle();
		/*
		 * update 2010-11-1 xie
		 */
		Log.d(TAG, "compress***********************compress");
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_COMPRESS);
		bundle.putInt(FileOp.KEY_INT_SRC_FROM, FileOp.SRC_FROM_CLIP);
		bundle.putString(FileOp.KEY_STRING_DEST_FILE_NAME, rarname);
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, path);
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_COMPRESS);
		if (rarname != null) {
			File newCompressFile = new File(path + "/" + rarname);
			if (newCompressFile.getName().toLowerCase()
					.contains(searchStr.toLowerCase()))
				fileArray.add(newCompressFile);
			sortedFileList(fileArray);
			itemList.notifyDataSetChanged();
			itemList.setListItems(directoryEntries);
			mlvContent.setAdapter(itemList);
		}
		Log.d(TAG, "compress------------------------------compress");
	}

	protected void getFileAttri(File file) {

		// Log.i(TAG,
		// "****************************** filesize = "+file.length());
		if (file.isFile() && !file.isHidden()) {
			fileNum++;
			fileSize += file.length();
			if (fileNum % 10 == 0)
				mAttributeThread.onAttributeResult();
			// return;
		} else if (file.isDirectory() && !file.isHidden()) {
			subDirNum++;
			if (subDirNum % 10 == 0)
				mAttributeThread.onAttributeResult();
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (mAttributeThread != null && mAttributeThread.mStop) {
					break;
				}
				getFileAttri(files[i]);
			}
		}
		if (mAttributeThread != null && !mAttributeThread.mStop)
			mAttributeThread.onAttributeResult();
	}

	private String transferSize(long lSize) {
		String size;
		int iPoint;
		if (lSize < 1024) {
			size = lSize + "B";
		} else if (lSize < 1024 * 1024) {
			size = String.valueOf(lSize / 1024.0);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "K";
		} else if (lSize < 1024 * 1024 * 1024) {
			size = String.valueOf(lSize / 1024.0 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "M";
		} else if (lSize < 1024L * 1024L * 1024L * 1024L) {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_G="+lSize);
			size = String.valueOf(lSize / 1024.0 / 1024 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "G";
		} else if (lSize < 1024L * 1024L * 1024L * 1024L * 1024L) {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_T="+lSize);
			size = String.valueOf(lSize / 1024.0 / 1024 / 1024 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "T";
		} else {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_Unknown="+lSize);
			size = getString(R.string.filesizeunknown);
		}

		return size;
	}

	private void disAttri() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%disAttri");
		subDirNum = -1;
		fileNum = 0;
		fileSize = 0;

		/*
		 * if (MarkedFile.isEmpty()) { Toast.makeText(this,
		 * R.string.error_file_does_not_exists, 3); return; }
		 */

		LayoutInflater factory = LayoutInflater.from(FileSearcher.this);
		View mtextEntryView = factory.inflate(R.layout.file_attri, null);
		TextView mFileName = (TextView) mtextEntryView
				.findViewById(R.id.filename);
		mSubDir = (TextView) mtextEntryView.findViewById(R.id.subdir);
		mSubFile = (TextView) mtextEntryView.findViewById(R.id.subfile);
		TextView mFileType = (TextView) mtextEntryView
				.findViewById(R.id.filetype);
		mTotalSize = (TextView) mtextEntryView.findViewById(R.id.totalsize);
		TextView mUpdateTime = (TextView) mtextEntryView
				.findViewById(R.id.updatetime);

		mAttributeThread = new MyAttributeThread(this) {
			public void run() {
				getFileAttri(MarkedFile.get(0));
			}
		};
		mAttributeThread.start();
		Date modifTime = new Date(MarkedFile.get(0).lastModified());
		String modiftime = DateFormat.getTimeFormat(getApplicationContext())
				.format(modifTime);
		String modifdate = DateFormat.getDateFormat(getApplicationContext())
				.format(modifTime);
		arrfilename = MarkedFile.get(0).getName();
		arrmodifyDate = modifdate + " " + modiftime;

		mFileName.setText(getResources().getString(R.string.filename)
				+ arrfilename);
		mUpdateTime.setText(getResources().getString(R.string.updatetime)
				+ arrmodifyDate);
		if (MarkedFile.get(0).isDirectory()) {
			mSubDir.setVisibility(View.VISIBLE);
			mSubFile.setVisibility(View.VISIBLE);
			mFileType.setVisibility(View.GONE);
		} else if (MarkedFile.get(0).isFile()) {
			mSubDir.setVisibility(View.GONE);
			mSubFile.setVisibility(View.GONE);
			mFileType.setVisibility(View.VISIBLE);

			int strId = R.string.unknownfile;
			if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingImage))) {
				strId = R.string.picturefile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingWebText))) {
				strId = R.string.htmlfile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingPackage))) {
				strId = R.string.compressfile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingAudio))) {
				strId = R.string.audiofile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingVideo))) {
				strId = R.string.videofile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingOffice))) {
				strId = R.string.Document;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingAndroid))) {
				strId = R.string.android_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".txt")) {
				strId = R.string.txt_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".pdf")) {
				strId = R.string.pdf_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".vcf")) {
				strId = R.string.vcf_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".csv")) {
				strId = R.string.csv_file;
			}
			mFileType.setText(getResources().getString(R.string.filetype)
					+ getResources().getString(strId));
		}

		new AlertDialog.Builder(FileSearcher.this)
				.setTitle(R.string.alert_dialog_attribute)
				.setView(mtextEntryView)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								if (mAttributeThread != null)
									mAttributeThread.toStop();
							}
						}).show();

	}

	/*
	 * open a dialog to list
	 */
	private void sendFile(File file) {
		FileShare.send(this, file);
	}

	private void onRename(File file) {
		if (TAG_FLAG) {
			Log.i(TAG, "==> onRename");
			Log.i(TAG,
					"the newFile path is===========" + file.getAbsolutePath());
			Log.i(TAG, "the newFile name is===========" + file.getName());
		}

		FileHandler.MsgHandler handler = new FileHandler.MsgHandler(
				FileRename.MSG_RES_OK, new MsgHandleFunc() {
					// @Override
					public boolean onMessage(Message msg) {
						// TODO Auto-generated method stub
						if (TAG_FLAG) {
							Log.d(TAG,
									"&&&&&&&&&&&******** has finish delete &&&&&&&&&&&&&********");
						}
						for (int i = 0; i < fileArray.size(); i++) {
							if (MarkedFile.get(0).getAbsoluteFile()
									.equals(fileArray.get(i).getAbsoluteFile())) {
								fileArray.remove(i);
								File newFile = new File(path + "/"
										+ FileRename.getNewName());
								if (newFile.getName().toLowerCase()
										.contains(searchStr.toLowerCase()))
									fileArray.add(newFile);
								break;
							}
						}
						if (TAG_FLAG) {
							Log.d(TAG, "MarkedFile============="
									+ MarkedFile.get(0).getAbsolutePath());
						}
						sortedFileList(fileArray);
						itemList.notifyDataSetChanged();
						itemList.setListItems(directoryEntries);
						mlvContent.setAdapter(itemList);
						if (fileArray == null || fileArray.size() == 0) {
							tView.setVisibility(View.VISIBLE);
							tView.setText(R.string.find_nothing);
						} else {
							tView.setVisibility(View.GONE);
						}
						return false;
					}
				});

		addMsgHandler(handler);
		FileRename.renameFile(this, file);
	}

	private void delFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%delFile");
		// add by xieqm 110418
		if(null != MarkedFile){
			String[] filePath = new String[MarkedFile.size()];
			for(int i=0;i<MarkedFile.size();i++){
				filePath[i] = MarkedFile.get(i).getAbsolutePath();
				if (false) {// NetDiskManager.isDownLoadWork(filePath[i])
					Log.d(TAG, "==> isDownLoadWork");
					ErrorMessageDialog.showMessageDialog(FileSearcher.this,
							getString(R.string.download_no_finish));
					break;
				} else if (true) {// NetDiskManager.isUpLoadWork(filePath[i])
					Log.d(TAG, "==> isUpLoadWork");
					ErrorMessageDialog.showMessageDialog(FileSearcher.this,
							getString(R.string.upload_no_finish));
					break;
				} else {
					deleteFile();
					break;
				}
			}
		}
		//end
	}
	
	private void deleteFile(){
		// protect system directory not to be deleted

		protectSysDir();
		if (MarkedFile.isEmpty()) {
			Toast.makeText(FileSearcher.this,
					R.string.error_file_does_not_exists, 3);
			return;
		}

		// added by wuqf 2010-10-21
		FileHandler.MsgHandler handler = new FileHandler.MsgHandler(
				FileDelete.MSG_RES_OK, new MsgHandleFunc() {
					public boolean onMessage(Message msg) {
						// TODO Auto-generated method stub
						if (TAG_FLAG) {
							Log.d(TAG,
									"&&&&&&&&&&&******** has finish delete &&&&&&&&&&&&&********");
							Log.d(TAG, "currentDirectory============="
									+ currentDirectory);
						}
						for (int i = 0; i < fileArray.size(); i++) {
							if (MarkedFile.get(0).getAbsoluteFile()
									.equals(fileArray.get(i).getAbsoluteFile())) {
								fileArray.remove(i);
								break;
							}
						}
						if (TAG_FLAG) {
							Log.d(TAG,
									"MarkedFile============="
											+ MarkedFile.get(0));
						}
						sortedFileList(fileArray);
						itemList.setListItems(directoryEntries);
						mlvContent.setAdapter(itemList);
						if (fileArray == null || fileArray.size() == 0) {
							tView.setVisibility(View.VISIBLE);
							tView.setText(R.string.find_nothing);
						} else {
							tView.setVisibility(View.GONE);
						}
						return false;
					}
				});
		addMsgHandler(handler);

		handler = new FileHandler.MsgHandler(FileDelete.MSG_RES_CANCEL,
				new MsgHandleFunc() {
					public boolean onMessage(Message msg) {
						// TODO Auto-generated method stub
						Toast.makeText(FileSearcher.this,
								R.string.cancelOpration, Toast.LENGTH_SHORT)
								.show();
						return false;
					}
				});
		addMsgHandler(handler);

		if (MarkedFile.size() == 1) {
			FileDelete.deleteOneFile(this, MarkedFile.get(0));
		} else if (MarkedFile.size() > 1) {
			Log.d("wuqf",
					"&&&&&&&&&&&&& marked file count: " + MarkedFile.size());
			FileClipBoard.getInstance().clear();
			FileClipBoard.getInstance().setOperation(FileClipBoard.OP_DELETE);
			for (int i = 0; i < MarkedFile.size(); i++) {
				File file = MarkedFile.get(i);
				if (!FileClipBoard.getInstance().hasIt(file)) {
					FileClipBoard.getInstance().addFile(file);
				}
			}
			FileDelete.deleteFilesInClip(this);
		}
		// end
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
		}
		cut_copy = false;

		switch (requestCode) {
		case Constant._ATTRIDISPLAY:
			switch (resultCode) {
			case RESULT_OK:
				/* get response form FileMan */
				Bundle bundle = data.getExtras();
				// TODO display the returned attributes
				LayoutInflater factory = LayoutInflater.from(this);
				final View textEntryView = factory.inflate(R.layout.file_attri,
						null);

				TextView tv = (TextView) textEntryView
						.findViewById(R.id.filename);
				String mfileName = bundle.getString("ARRFILENAME");
				tv.setText(this.getResources().getString(R.string.filename)
						+ mfileName);

				tv = (TextView) textEntryView.findViewById(R.id.subdir);
				String nDir = bundle.getString("ARRSUBDIR");
				if (nDir == null || nDir.length() == 0) {
					tv.setVisibility(View.GONE);
				} else {
					tv.setText(this.getResources().getString(R.string.subdir)
							+ nDir);
				}

				tv = (TextView) textEntryView.findViewById(R.id.subfile);
				String nFile = bundle.getString("ARRFILENUM");
				if (nFile == null || nFile.length() == 0) {
					tv.setVisibility(View.GONE);

					int strId = R.string.unknownfile;
					if (checkEndsWithInStringArray(mfileName, getResources()
							.getStringArray(R.array.fileEndingImage))) {
						strId = R.string.picturefile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingWebText))) {
						strId = R.string.htmlfile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingPackage))) {
						strId = R.string.compressfile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingAudio))) {
						strId = R.string.audiofile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingVideo))) {
						strId = R.string.videofile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingOffice))) {
						strId = R.string.Document;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingAndroid))) {
						strId = R.string.android_file;
					} else if (FileUtil.getExtension(mfileName).equals(".txt")) {
						strId = R.string.txt_file;
					} else if (FileUtil.getExtension(mfileName).equals(".pdf")) {
						strId = R.string.pdf_file;
					} else if (FileUtil.getExtension(mfileName).equals(".vcf")) {
						strId = R.string.vcf_file;
					} else if (FileUtil.getExtension(mfileName).equals(".csv")) {
						strId = R.string.csv_file;
					}

					tv = (TextView) textEntryView.findViewById(R.id.filetype);
					tv.setText(this.getResources().getString(R.string.filetype)
							+ getResources().getString(strId));
				} else {
					tv.setText(this.getResources().getString(R.string.filenum)
							+ nFile);
					tv = (TextView) textEntryView.findViewById(R.id.filetype);
					tv.setVisibility(View.GONE);
				}
				tv = (TextView) textEntryView.findViewById(R.id.totalsize);
				String size = bundle.getString("ARRTOTALFILESIZE");
				tv.setText(this.getResources().getString(R.string.totalsize)
						+ size);

				if (bundle.getString("ARRMODIRYDATE") != null) {
					tv = (TextView) textEntryView.findViewById(R.id.updatetime);
					String uTime = bundle.getString("ARRMODIRYDATE");
					tv.setText(this.getResources().getString(
							R.string.updatetime)
							+ uTime);
				}

				new AlertDialog.Builder(FileSearcher.this)
						.setTitle(R.string.alert_dialog_attribute)
						.setView(textEntryView)
						.setPositiveButton(R.string.alert_dialog_ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
									}
								}).show();
				break;
			}
			break;
		case FileOp.FOP_DELETE:
			switch (resultCode) {
			case RESULT_OK:
				Log.d(TAG, "delete-----------refresh");
				// State = _LIST;
				// initState();
			}
		default:
			break;

		}
	}

	public void exit() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%exit");
		System.exit(0);
	}

	/*
	 * add 2010-11-4 xie
	 */
	private void protectSysDir() {
		Log.d(TAG, "protectSysDir");
		boolean hasSysDir = false;
		String alertStr = null;
		// List<File> sysList = getSysDir();
		List<File> removeList = new ArrayList<File>();
		removeList.clear();
		if (MarkedFile.isEmpty())
			return;
		else {
			for (int i = 0; i < MarkedFile.size(); i++) {
				if (Constant.isSysOrReservedDir(this, MarkedFile.get(i))) {
					hasSysDir = true;
					removeList.add(MarkedFile.get(i));

					if (alertStr == null)
						alertStr = Constant.textConvert(this, MarkedFile.get(i)
								.getName());
					else
						alertStr += ", "
								+ Constant.textConvert(this, MarkedFile.get(i)
										.getName());
				}

			}
		}
		// added by wuqf
		if (hasSysDir == true) {
			if (cut_copy) {
				alertStr += getResources().getString(R.string.cut_alert);
				Toast.makeText(FileSearcher.this, alertStr, Toast.LENGTH_SHORT)
						.show();
			}
		}
		// end
		if (!removeList.isEmpty())
			MarkedFile.removeAll(removeList);
	}

	public void onTitleIconClick() {
		finish();
	}

	@Override
	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		boolean bContained = pathname.getName().toLowerCase()
				.contains(searchStr.toLowerCase());
		if (bContained == true) {
			return true;
		} else {
			if (pathname.isDirectory()) {
				File[] files = pathname.listFiles();
				if (files == null || files.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}

		return false;
	}

	private BroadcastReceiver SdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(intent.ACTION_MEDIA_UNMOUNTED)
					|| action.equals(Intent.ACTION_MEDIA_REMOVED)
					|| action.equals(Intent.ACTION_MEDIA_SHARED)) {
				finish();
			}
		}
	};

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG, "#####################onSaveInstanceState#################");
		// outState.putLong("id", 1234567890);
		outState.putSerializable("result", fileArray);
		outState.putBoolean("flag", true);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long id) {
		File file = directoryEntries.get(position).getFile();
		if (file.isDirectory() == true) {
			Bundle bundle = new Bundle();
			bundle.putString("destination", directoryEntries.get(position)
					.getFile().getAbsolutePath().toString());
			bundle.putBoolean("dirFlag", true);
			Intent mIntent = new Intent();
			mIntent.putExtras(bundle);
			setResult(RESULT_OK, mIntent);
			finish();
		} else {
			FileBrowser.getInstance()
					.FileManagerOpenFile(
							directoryEntries.get(position).getFile(),
							FileSearcher.this);
		}
	}
}